package com.lyr.test.service;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class MyServiceImpl implements MyService {

    DataSource dataSource;
    PlatformTransactionManager transactionManager;

    public MyServiceImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public MyServiceImpl(DataSource dataSource, PlatformTransactionManager transactionManager) {
        this.dataSource = dataSource;
        this.transactionManager = transactionManager;
    }

    @Override
    public String performAction(String action) throws Exception {
        System.out.println("Performing action in MyService: " + action);
        if ("throw".equals(action)) {
            throw new Exception("Exception from MyService");
        }
        return "Action performed: " + action;
    }

    @Override
    public String doTx() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

        }
        catch (Exception ex) {
            transactionManager.rollback(status);
            throw ex;
        }
        transactionManager.commit(status);
        return "OK";
    }
}
